const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
// 引入tDesign消息提示组件
import Message from 'tdesign-miniprogram/message/index';

// pages/cash/cash.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        // 导航栏数据
        styledata: {
            "bg_color": "#fff",
            "color": "#000",
            "name": "零钱中心",
            "leftflag": true,
            // "homeflag": true,
        },

        // ts组件对话框的 确认取消按钮
        confirmBtn: { content: '前往认证', variant: 'base' },
        isShowjump: false,

        showIdentify: false,
        showBindbank: false,

        // 是否正在实名认证
        Identiting: false,
        // 是否正在绑卡申请
        BindCarding: false,

        // 实名认证模态框y轴移动距离
        idenmoveNum: '-205%',
        // 银行卡绑定模态框y轴移动距离
        cardmoveNum: '-205%',

        uid: '',
        userInfo: {},
        isVip: false,

        // 可提现金额
        availableMoney: "0.00",

        textfont: "发送验证码"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        await this.initData(options)

        // this.queryBalance()
        await this.queryWmemberInfo()
    },

    async initData(options) {
        await App.getMyFullInfo()
        this.setData({
            userInfo: App.globalData.fulluserInfo,
            isVip: App.globalData.isVip,
            // isVip: true,
            uid: App.globalData.uid
            // uid: 7486
            // uid: 7455

        })
    },

    // 检测是否为分销员
    checkIsDistributor() {
        let allinMoblie = this.wDetail?.allin_moblie ? this.wDetail.allin_moblie : ""
        let isVip = this.data.isVip
        console.log(allinMoblie, isVip);
        let isdistri = allinMoblie.length > 0 && isVip ? true : false
        return isdistri
    },

    confirmDialog() {
        this.setData({ isShowjump: false });
        wx.navigateTo({
            url: '/distribution/distributor/distributor',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    closeDialog() {
        this.setData({ isShowjump: false });
        // wx.navigateBack({
        //     delta: 1
        // });
    },

    // 提现回调
    goWithDraw() {
        // let isDistri = this.checkIsDistributor()
        // 积分换零后亦可提现 这里暂时不用判断是否为分销员 
        let isDistri = true

        // 验证是否已绑定手机
        let allinMoblie = this.wDetail?.allin_moblie ? this.wDetail.allin_moblie : ""
        if (allinMoblie.length !== 11) {
            this.goBindPhone()
            return
        }

        // 非分销员，弹窗提示前往认证页面
        console.log("isDistri", isDistri);
        if (!isDistri) {
            this.setData({
                isShowjump: true
            })
        }
        // 依次验证实名、银行卡绑定
        else {
            let isIdentity = this.wDetail.allin_identity
            let hasBankCard = this.wDetail.allin_withdraw_card
            let acct_protocol_no = this.wDetail.acct_protocol_no

            console.log("isIdentity, hasBankCard, acct_protocol_no", isIdentity, hasBankCard, acct_protocol_no);
            // 未实名 
            if (isIdentity == "") {
                this.showIdenModal()
                return
            }

            // 已实名 未绑卡
            if (isIdentity !== "" && hasBankCard == "") {
                this.showCardModal()
                return
            }

            // 已实名 已绑卡 未提现签约(不用空字符串判断，因为数据库为null值)
            if (isIdentity !== "" && hasBankCard !== "" && acct_protocol_no == "") {
                this.askToSign()
                return
            }

            this.gotoWithdraw()
        }
    },


    // 跳转提现页面
    gotoWithdraw() {
        wx.navigateTo({
            url: '/pages/cash/withdraw',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    goBindPhone() {
        this.showErrorMessage("您未绑定手机，即将跳转绑定噢~")
        let timer = setTimeout(() => {
            clearTimeout(timer)
            util.showLoading("跳转中")
            let timer2 = setTimeout(() => {
                clearTimeout(timer2)
                util.hideLoading()
                wx.navigateTo({
                    url: '/distribution/choice/choice?current=0',
                    success: (result) => {

                    },
                    fail: () => { },
                    complete: () => { }
                });
            }, 1000);
        }, 2500);
    },

    // 询问是否进行提现签约页面跳转
    async askToSign() {
        let content = "您未进行提现签约，是否前往签约"
        let title = "提现签约"
        const that = this
        wx.showModal({
            title,
            content,
            showCancel: true,
            // confirmText: text,
            async success(res) {
                if (res.confirm) {
                    let url = await that.getSignUrl()
                    that.gotoSignAcct(url)
                    // console.log(url);
                    // if (url == "") return
                    // setTimeout(() => {
                    // that.jumpSignUrl()
                    // }, 2500);
                } else if (res.cancel) {
                    util.showToast('已取消')
                }
            }
        })
    },

    // 跳转签约页面
    jumpSignUrl() {
        let params = {
            uid: this.data.uid,
            name: this.wDetail.true_name
        }
        wx.navigateTo({
            url: `/distribution/signacct/signacct?params=${JSON.stringify(params)}`,
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });
    },

    // 点击认证按钮回调
    async confirmIdentity() {
        let result = await this.sendIdentity()
        console.log('confirmIdentity', result);
        if (result) {
            this.closeIdentity()
            // 手动调用提现功能 自动判断拉起银行卡绑定
            this.goWithDraw()
        }
    },

    // 弹出实名认证模态框
    showIdenModal() {
        this.setData({
            idenmoveNum: '-50%'
        })
    },

    // 弹出银行卡绑定模态框
    showCardModal() {
        // 出修改框
        this.setData({
            cardmoveNum: '-50%'
        })
    },

    //关闭实名认证模态框
    closeIdentity() {
        this.setData({
            idenmoveNum: '-205%',
            idenName: '',
            idenCardNum: ''
        })
    },

    //关闭银行卡绑定模态框
    closeBindCard() {
        this.setData({
            cardmoveNum: '-205%',
            bankCardNum: '',
            bankMoblie: '',
            bankCode: ''
        })
    },

    // 获取对应的输入框的输入值
    inputBlur(e) {
        let valname = e.currentTarget.dataset.valname
        console.log("e.detail.value", e.detail.value);
        this.setData({
            [`${valname}`]: e.detail.value
        })
    },

    // 发送实名认证请求
    async sendIdentity() {

        let uid = this.data.uid
        let name = this.data.idenName
        let idcode = this.data.idenCardNum
        console.log(uid, name, idcode);
        if (!uid || !name || !idcode) {
            return util.showToast("请完善实名认证信息")
        }

        let params = {
            uid,
            name,
            idcode,
            idtype: 1
        }

        this.setData({
            Identiting: true,
        })
        let identityInfo = await request.postall(api.setRealName, params)
        this.setData({
            Identiting: false,
        })
        console.log("identityInfo", identityInfo);
        // identityInfo.code = 0
        if (identityInfo.code == 0) {
            this.showSuccessMessage(identityInfo.msg)
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    // 更新用户信息
                    await this.initData()
                    await this.queryWmemberInfo()
                    resolve(true)
                }, 2500);
            })

        } else {
            this.showErrorMessage(identityInfo.msg)
            return false
        }
    },

    // 发送银行卡请求（获取手机验证码）
    async applyBindcode() {

        console.log("wDetail", this.wDetail);
        let uid = this.data.uid
        let name = this.wDetail.true_name
        let idcode = this.wDetail.allin_identity
        let bankCardNum = this.data.bankCardNum
        let moblie = this.data.bankMoblie

        // console.log(!uid, !name, !idcode);
        if (!bankCardNum || !moblie) {
            return util.showToast("请完善绑卡信息")
        }

        let params = {
            uid,
            name,
            idcode,
            idtype: 1,
            moblie,
            cardno: bankCardNum
        }

        console.log(params);
        let codeRes = await request.postall(api.applyBankCard, params)
        console.log(codeRes);
        if (codeRes.code == 0) {
            // 验证码发送成功 限制发送间隔
            this.changetip()
            this.bindCardInfo = codeRes.data
            this.showSuccessMessage(codeRes.msg)
            return true
        } else {
            this.showErrorMessage(codeRes.msg)
            return false
        }
    },

    // 绑定银行卡申请
    async confirmBindCard() {
        let bankCode = this.data.bankCode
        let bindCardInfo = this.bindCardInfo
        if (bankCode == '') {
            return util.showFail("请填写验证码")
        }

        let params = {
            uid: this.data.uid,
            moblie: this.data.bankMoblie,
            cardno: this.data.bankCardNum,
            tranceNum: bindCardInfo.tranceNum,
            code: bankCode
        }

        this.setData({
            BindCarding: true,
        })
        let bindResult = await request.postall(api.bindBankCard, params)
        this.setData({
            BindCarding: false,
        })
        console.log("bindResult", bindResult);
        // bindResult.code = 0
        if (bindResult.code == 0) {
            this.showSuccessMessage(bindResult.msg)
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    // 关闭绑定银行卡模态框
                    this.closeBindCard()
                    // 更新用户信息
                    await this.initData()
                    // 更新查询提现会员信息（主要获取提现签约信息）
                    await this.queryWmemberInfo()
                    // 手动调用提现功能 
                    this.goWithDraw()
                    resolve(true)
                }, 2500);
            })

        } else {
            // util.showFail(bindResult.msg)
            this.showErrorMessage(bindResult.msg)
            return false
        }
    },

    // 查询会员提现余额
    async queryBalance() {
        let Balance = await request.post(api.checkAllinBalance, { uid: this.data.uid })
        Balance = Balance ? Balance : 0
        let allAmount = (Balance.allAmount / 100).toFixed(2)
        // console.log("余额", Balance, allAmount);
        this.setData({
            availableMoney: allAmount
        })
    },

    // 查询提现人员详细信息
    async queryWmemberInfo() {
        let wDetail = await request.post(api.queryWmemberInfo, { uid: this.data.uid })
        console.log("提现人详情", wDetail);

        // 提现人员详情不显示在页面 无需记录在data中
        this.wDetail = wDetail ? wDetail : {}
    },

    // 获取提现签约页面
    async getSignUrl() {
        let params = {
            uid: this.data.uid,
            name: this.wDetail.true_name
        }
        util.showLoading()
        let signRes = await request.postall(api.applySignAcct, params)
        util.hideLoading()
        console.log("签约页面", signRes);
        if (signRes.code == 0) {
            this.showSuccessMessage(signRes.msg)
            return signRes.data.url
        } else {
            this.showErrorMessage(signRes.msg)
            return ''
        }
    },

    // 跳转签约小程序
    gotoSignAcct(targetURL) {
        wx.navigateToMiniProgram({
            appId: 'wxc46c6d2eed27ca0a', // 通联的提现签约页面小程序
            path: "pages/merchantAddress/merchantAddress",
            extraData: {  // 将提现申请获得的url作为参数传递过去
                targetUrl: targetURL
            },
            success(res) {
                // 打开成功的回调
            },
            fail(err) {
                // 打开失败的回调
            }
        });
    },

    // 错误提示
    showErrorMessage(content) {
        Message.error({
            context: this,
            offset: [144, 130],
            duration: 2500,
            content: content,
        });
    },
    // 成功提示
    showSuccessMessage(content) {
        Message.success({
            context: this,
            offset: [144, 130],
            duration: 2500,
            content: content,
        });
    },

    // 倒数提示
    changetip(num = 60) {
        this.setData({
            isForbid: true
        })
        let timer = setInterval(() => {
            if (num == 1) {
                this.setData({
                    isForbid: false,
                    textfont: `发送验证码`
                })
                clearInterval(timer)
                return
            }

            num--
            this.setData({
                textfont: `重新发送${num}`
            })
        }, 1000);
    },

    // 验证6位数字验证码
    isValidCode(code) {
        return /^\d{6}$/.test(code);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.queryBalance()

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let returnOptions = wx.getEnterOptionsSync();

        console.log(returnOptions.scene, returnOptions.referrerInfo.appId, returnOptions.path, returnOptions.referrerInfo.extraData);
        if (returnOptions.scene == '1038' && returnOptions.referrerInfo.appId == 'wxc46c6d2eed27ca0a') {
            returnOptions.scene = ""
            returnOptions.referrerInfo.appId = ""
            // 如果是从通联签约小程序返回 延迟0.5s重新获取数据 并做提示
            let timer = setTimeout(async () => {
                clearTimeout(timer)
                await this.queryWmemberInfo()
                if (this.wDetail.acct_protocol_no !== "") {
                    this.showSuccessMessage("已成功签约提现协议")
                } else {
                    this.showErrorMessage("签约提现协议未完成，请稍后重试")
                }
            }, 500);
        }
        // 更新提现用户信息（认证中心绑定手机返回）
        if (returnOptions.scene == "1089" && returnOptions.path == "pages/home/home") {
            this.queryWmemberInfo()
        }
        this.queryBalance()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})